﻿(function ($) {
    $.fn.epicGrid = function (options) {
        var defaultOptions =
        {
            'contenttype': '',
            'gridItemSelector': '.grid-items-list',
            'messageSelector': '.yellow-message',
            'timer': '',
            'filter': '',
            'downKey': 40,
            'upKey': 38,
            'selectKey': 32,
            'deleteKey': 46,
            'completeKey': 35,
            'deleteFunction': null,
            'editFunction': null,
            'archiveFuntion': null,
            'pinFunction': null,
            'refreshFunction': null,
            'editButtons': null,
            'barButtonHtml': '<div class="grey-item grey-button ##name##-button image-button" tip="##tip##">##text##</div>',
            'globalButtonNames': ["filter", "add"],
            'editButtonNames': ["pin", "edit", "archive", "delete"],
            'view_first_part': '<div class="view-row"><div class="view-name">',
            'view_middle_part': '</div><div class="view-value">',
            'view_last_part': '</div></div>',
            'arrowHTML': '<div class="selected-item"></div>'
        };
        var o = $.extend(defaultOptions, options);
        
        return this.each(function () {
            var $t = $(this);

            function init() {
                var editButtonSelector = configureButtons();
                o.editButtons = $t.find(editButtonSelector);
                o.editButtons.hide();

                configureButtonEvents();
                configureCheckboxes($t);
                configureGridItemClick();
            }            

            function callRefresh() {
                if (o.refreshFunction != null)
                    o.refreshFunction();
            }

            function configureCheckboxes() {
                $t.find('.selectall').bind('click', function () {
                    if ($(this).is(':checked')) {
                        $(o.gridItemSelector).find(':checkbox:not(:checked)').attr('checked', 'checked').change();
                        //enableGridButtons();
                    } else {
                        $(o.gridItemSelector).find(':checkbox:checked').removeAttr('checked').change();
                        //disableGridButtons();
                    }
                });

                // Turn item bar yellow on checkbox click
                $(o.gridItemSelector).delegate(':checkbox', 'change', function () {
                    if ($(this).is(':checked')) {
                        $(this).parents('.grid-item').addClass('checked-grid-item-bar');
                        enableGridButtons();
                    } else {
                        $(this).parents('.grid-item').removeClass('checked-grid-item-bar');
                        if ($(o.gridItemSelector).find(":checked").length === 0) {
                            // Make complete and delete item buttons look disabled
                            disableGridButtons();
                        }
                    }
                });
            }

            function configureButtons() {
                var editButtonSelector = "";

                // Create the global buttons
                for (var i in o.globalButtonNames) {
                    var globalButtonHtml = o.barButtonHtml;
                    var camelName = o.globalButtonNames[i][0] = o.globalButtonNames[i][0].toUpperCase();
                    if (o.globalButtonNames[i].length > 1)
                        camelName += o.globalButtonNames[i].substr(1, o.globalButtonNames[i].length);
                    globalButtonHtml = globalButtonHtml.replace(/##name##/, o.globalButtonNames[i]);
                    globalButtonHtml = globalButtonHtml.replace(/##tip##/, camelName);
                    globalButtonHtml = globalButtonHtml.replace(/##text##/, camelName);
                    $t.find('.global-buttons').append(globalButtonHtml);
                }

                // Create the edit buttons
                for (var i in o.editButtonNames) {
                    editButtonSelector += ", ." + o.editButtonNames[i] + "-button";
                    var editButtonHtml = o.barButtonHtml;
                    var camelName = o.editButtonNames[i][0] = o.editButtonNames[i][0].toUpperCase();
                    if (o.editButtonNames[i].length > 1)
                        camelName += o.editButtonNames[i].substr(1, o.editButtonNames[i].length);
                    editButtonHtml = editButtonHtml.replace(/##name##/, o.editButtonNames[i]);
                    editButtonHtml = editButtonHtml.replace(/##tip##/, camelName);
                    editButtonHtml = editButtonHtml.replace(/##text##/, camelName);;
                    $t.find('.edit-buttons').append(editButtonHtml);
                }
                editButtonSelector = editButtonSelector.replace(",", "");
                return editButtonSelector;
            }

            function configureButtonEvents() {
                // Refresh the grid results
                $t.find('.refresh-button').bind('click', function () {
                    if (o.refreshFunction != null)
                        o.refreshFunction();

                    callRefresh();
                });

                // Add an item
                $t.find('.add-button').bind('click', function () {
                    if (o.addFunction != null)
                        o.addFunction();
                });

                // Edit the selected items
                $t.find('.edit-button').bind('click', function () {
                    if (o.editFunction != null)
                        o.editFunction();

                    clearCheckedItems(' items moved to trash', false);
                    disableGridButtons();
                });

                // Delete the selected items
                $t.find('.delete-button').bind('click', function () {
                    if (o.deleteFunction != null)
                        o.deleteFunction();

                    clearCheckedItems(' items moved to trash', false);
                    disableGridButtons();
                });

                // Complete the selected item
                $t.find('.archive-button').bind('click', function () {
                    if (o.archiveFunction != null)
                        o.archiveFunction();

                    clearCheckedItems(' items archived', true);
                    disableGridButtons();
                });

                // Complete the selected item
                $t.find('.pin-button').bind('click', function () {
                    if (o.pinFunction != null)
                        o.pinFunction();

                    clearCheckedItems(' items pinned', true);
                    disableGridButtons();
                });

                $t.find('.filter-button').bind('click', function () {
                    var filter = $(this).parent().siblings('#filterText').val();
                    if (filter == o.filter) {
                        return;
                    }
                    if (filter === "") {
                        $(o.gridItemSelector).find('.grid-item').show();
                        return;
                    }
                    o.filter = filter;
                    filterItems(o.filter);
                });
            }
            
            function configureGridItemClick() {
                // Add click event to the grid item content area for viewing the item
                $(o.gridItemSelector).delegate('.grid-item-content-area', 'click', function () {
                    // Show loading animation
                    $('#view-items-list').empty();

                    $(o.gridItemSelector).find('.selected-grid-item-bar').removeClass('selected-grid-item-bar');
                    $(this).addClass('selected-grid-item-bar');

                    var getDataMethod = '/d/' + o.contenttype + '/' + $(this).find('.id-tag').html();
                    var getDataMethodParams = '';
                    if (o.contenttype == "dynamic") {
                        getDataMethod = '/m/sp_getContentById';
                        getDataMethodParams = 'id=' + $(this).find('.id-tag').html();
                    }
                    getData(getDataMethod, getDataMethodParams, showDataInViewer, false, '', $(this), "");
                });
            }

            function showDataInViewer(data, target, unused) {
                var view_html = "";

                for (var key in data[0]) {
                    view_html = o.view_first_part + key + o.view_middle_part + data[0][key] + o.view_last_part;
                    $('#view-items-list').append(view_html);
                }
            }

            // Listen for keydown for item list navigation
            // Use keydown on document for better compatibility
            //$(document).bind('keydown', function (e) {
            //    // ignore keypress if it is in a text input or textarea
            //    if (e.target.type !== "text" && e.target.tagName !== "TEXTAREA") {
            //        listenForGridKeyDown(e);
            //    }
            //});

            function filterItems(term) {
                var results = $(o.gridItemSelector).find('.grid-item:contains(' + term + ')');

                if (results.length === 0) {
                    $(o.gridItemSelector).find('.grid-item').fadeOut();
                    return;
                }
                var excess = $(o.gridItemSelector).find('.grid-item:not(:contains(' + term + '))');

                excess.fadeOut();
                results.show();
            }

            function clearCheckedItems(message, fade) {
                var selectedItems = $(o.gridItemSelector).find(":checked");

                // Prevent the arrow from being prepended if nothing's checked
                if (selectedItems.length === 0) {
                    // Alert the user that nothing's checked with a yellow alert message
                    ShowMessage('No items selected');
                    return false;
                }

                // Alert the user what's been removed
                removeItems(selectedItems, selectedItems.length + message, fade)
            }

            function removeItems(removeList, message, fadeout) {
                if (fadeout === true) {
                    removeList.parents('.grid-item').fadeOut('slow', function () {
                        $(this).remove();
                    });
                }
                else {
                    removeList.parents('.grid-item').remove();
                }
                ShowMessage(message);
            }

            function ShowMessage(msg) {
                if (msg === '') {
                    $(o.messageSelector).hide();
                } else {
                    $(o.messageSelector).html(msg).show();
                    clearTimeout(o.timer);
                    o.timer = setTimeout(function () { $(o.messageSelector).hide().empty(); }, 15000);
                }
            }

            function disableGridButtons() {
                o.editButtons.fadeOut();
            }

            function enableGridButtons() {
                if (o.editButtons.is(':visible') != true) {
                    o.editButtons.fadeIn();
                }
            }

            init();
        });
    }
})(jQuery);